import {createOrder, queryOrder} from '../../request/order'
import { getPayInfo } from "../../request/pay";
import {showToast} from '../../utils/asyncWx'

Page({
  data: {
    address: {},
    cate: [],
    totalPrice: 0,
    totalNum: 0
  },
  onLoad: function () {
    const address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];
    cart = cart.filter(v => v.checked);
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })
    this.setData({
      cart, totalPrice, totalNum, address
    });
  },

  async  handleOrderPay() {
    try {
      const token = wx.getStorageSync('token')
      if (!token) {
        wx.navigateTo({url:'/pages/auth/index'})
        return
      }
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address.all
      const {cart} = this.data
      let goods = []
      cart.forEach(value => {
        goods.push({
          goods_id: value.goods_id,
          goods_number: value.num,
          goods_price: value.goods_price
        })
      })
      const orderParams = {order_price, consignee_addr, goods}
      //创建订单获取支付参数
      const {order_number} = await createOrder(orderParams)
      //发起预支付接口
      const pay = await getPayInfo(order_number)
      //发起微信支付
      wx.requestPayment(pay)
      //查询订单
      const res = await queryOrder(order_number)
      await showToast({title: '支付成功'})
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(value => !value.checked)
      wx.setStorageSync('cart',newCart)
      wx.navigateTo({
        url: '/pages/order/index'
      })
    } catch (error) {
      await showToast({title: '支付失败'})
      console.log(error);
    }
  },
})